package com.mexico.inloancash.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.os.storage.StorageManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.mexico.inloancash.MyApplication;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.India_UserImage_ListBean;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.http.IndiaRequestApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.Context.TELEPHONY_SERVICE;
import static android.content.Context.WIFI_SERVICE;

public class DeviceIdUtil {
    /**
     * 获得设备硬件标识
     *
     * @param context 上下文
     * @return 设备硬件标识
     */
    public static String getDeviceId(Context context) {
        StringBuilder sbDeviceId = new StringBuilder();

        //获得设备默认IMEI（>=6.0 需要ReadPhoneState权限）
        String imei = getIMEI(context);
        //获得AndroidId（无需权限）
        String androidid = getAndroidId(context);
        //获得设备序列号（无需权限）
        String serial = getSERIAL();
        //获得硬件uuid（根据硬件相关属性，生成uuid）（无需权限）
        String uuid = getDeviceUUID().replace("-", "");

        //追加imei
        if (imei != null && imei.length() > 0) {
            sbDeviceId.append(imei);
            sbDeviceId.append("|");
        }
        //追加androidid
        if (androidid != null && androidid.length() > 0) {
            sbDeviceId.append(androidid);
            sbDeviceId.append("|");
        }
        //追加serial
        if (serial != null && serial.length() > 0) {
            sbDeviceId.append(serial);
            sbDeviceId.append("|");
        }
        //追加硬件uuid
        if (uuid != null && uuid.length() > 0) {
            sbDeviceId.append(uuid);
        }

        //生成SHA1，统一DeviceId长度
        if (sbDeviceId.length() > 0) {
            try {
                byte[] hash = getHashByString(sbDeviceId.toString());
                String sha1 = bytesToHex(hash);
                if (sha1 != null && sha1.length() > 0) {
                    //返回最终的DeviceId
                    return sha1;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        //如果以上硬件标识数据均无法获得，
        //则DeviceId默认使用系统随机数，这样保证DeviceId不为空
        return UUID.randomUUID().toString().replace("-", "");
    }

    //需要获得READ_PHONE_STATE权限，>=6.0，默认返回null
    @SuppressLint("MissingPermission")
    private static String getIMEI(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager)
                    context.getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getDeviceId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备的AndroidId
     *
     * @param context 上下文
     * @return 设备的AndroidId
     */
    private static String getAndroidId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备序列号（如：WTK7N16923005607）, 个别设备无法获取
     *
     * @return 设备序列号
     */
    private static String getSERIAL() {
        try {
            return Build.SERIAL;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获得设备硬件uuid
     * 使用硬件信息，计算出一个随机数
     *
     * @return 设备硬件uuid
     */
    private static String getDeviceUUID() {
        try {
            String dev = "3883756" +
                    Build.BOARD.length() % 10 +
                    Build.BRAND.length() % 10 +
                    Build.DEVICE.length() % 10 +
                    Build.HARDWARE.length() % 10 +
                    Build.ID.length() % 10 +
                    Build.MODEL.length() % 10 +
                    Build.PRODUCT.length() % 10 +
                    Build.SERIAL.length() % 10;
            return new UUID(dev.hashCode(),
                    Build.SERIAL.hashCode()).toString();
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    /**
     * 取SHA1
     *
     * @param data 数据
     * @return 对应的hash值
     */
    private static byte[] getHashByString(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.reset();
            messageDigest.update(data.getBytes("UTF-8"));
            return messageDigest.digest();
        } catch (Exception e) {
            return "".getBytes();
        }
    }

    /**
     * 转16进制字符串
     *
     * @param data 数据
     * @return 16进制字符串
     */
    private static String bytesToHex(byte[] data) {
        StringBuilder sb = new StringBuilder();
        String stmp;
        for (int n = 0; n < data.length; n++) {
            stmp = (Integer.toHexString(data[n] & 0xFF));
            if (stmp.length() == 1)
                sb.append("0");
            sb.append(stmp);
        }
        return sb.toString().toUpperCase(Locale.CHINA);
    }

    /**
     * 返回系统上次开机时间
     *
     * @return
     */
    public static long getElapsedRealtime() {
        long resultTime = 0;
        try {
            //public static long elapsedRealtime ()   返回系统启动到现在的毫秒数，包含休眠时间。 参考API
            long time = SystemClock.elapsedRealtime();
            long currentTime = System.currentTimeMillis();
            resultTime = currentTime - time;
            if (resultTime < 0) {
                resultTime = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultTime;
    }


    /**
     * 获得机身内存大小  这里认为是内置的sdcard
     *
     * @return
     */
    public static long getRomTotalSize() {
        long size = 0;
        try {
            File path = Environment.getDataDirectory();
            StatFs statFs = new StatFs(path.getPath());
            long blockSize = statFs.getBlockSizeLong();
            long tatalBlocks = statFs.getBlockCountLong();
            size = blockSize * tatalBlocks;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 获得机身剩余内存大小 这里认为是内置的sdcard
     *
     * @return
     */
    public static long getRomSYTotalSize() {
        long size = 0;
        try {
            File path = Environment.getDataDirectory();
            StatFs statFs = new StatFs(path.getPath());
            long blockSize = statFs.getBlockSizeLong();
            long availCount = statFs.getAvailableBlocksLong();
            size = blockSize * availCount;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }


    /**
     * 获取 内存卡大小（单位字节）  如果手机没有外置sdcard的话 这样获取的也是内置的sdcard信息
     */
    public static long readSDCard() {
        long size = 0;
        try {
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File sdcardDir = Environment.getExternalStorageDirectory();
                StatFs sf = new StatFs(sdcardDir.getPath());
                long blockSize = sf.getBlockSizeLong();
                long blockCount = sf.getBlockCountLong();
                size = blockSize * blockCount;
                if (size < 0) {
                    size = 0;
                }
                //long availCount = sf.getAvailableBlocksLong();
                //Log.e("data", "block大小:"+ blockSize+",block数目:"+ blockCount+",总大小:"+blockSize*blockCount/1024+"KB");
                //Log.e("data", "可用的block数目：:"+ availCount+",剩余空间:"+ availCount*blockSize/1024+"KB");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 获取内存卡已使用量（单位字节）
     *
     * @return
     */
    public long readSDCardUsed() {
        long total = 0;
        long used = 0;
        try {
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File sdcardDir = Environment.getExternalStorageDirectory();
                StatFs sf = new StatFs(sdcardDir.getPath());
                long blockSize = sf.getBlockSizeLong();
                long blockCount = sf.getBlockCountLong();
                long availCount = sf.getAvailableBlocksLong();
                total = blockSize * blockCount;
                long remaining = availCount * blockSize;//剩余的空间
                used = total - remaining;//得到已使用的空间
                if (used < 0) {
                    used = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return used;
    }


    /**
     * 获取内存卡可使用量（单位字节）
     *
     * @return
     */
    public static long readSDRemaining() {
        long re = 0;
        try {
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state)) {
                File sdcardDir = Environment.getExternalStorageDirectory();
                StatFs sf = new StatFs(sdcardDir.getPath());
                long blockSize = sf.getBlockSizeLong();
                long blockCount = sf.getBlockCountLong();
                long availCount = sf.getAvailableBlocksLong();
                re = availCount * blockSize;//剩余的空间
                if (re < 0) {
                    re = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return re;
    }

    /**
     * 获取真实物理屏幕尺寸
     *
     * @param context
     * @return
     */
    public static double getPhysicsScreenSize(Activity context) {
        double result = 0;
        try {
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point point = new Point();
            manager.getDefaultDisplay().getRealSize(point);
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            int densityDpi = dm.densityDpi;//得到屏幕的密度值，但是该密度值只能作为参考，因为他是固定的几个密度值。
            double x = Math.pow(point.x / dm.xdpi, 2);//dm.xdpi是屏幕x方向的真实密度值，比上面的densityDpi真实。
            double y = Math.pow(point.y / dm.ydpi, 2);//dm.xdpi是屏幕y方向的真实密度值，比上面的densityDpi真实。
            double screenInches = Math.sqrt(x + y);
            BigDecimal b = new BigDecimal(screenInches);
            result = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取cpu核心数
     *
     * @return
     */
    public static int getPhoneCore() {
        int core = 0;
        try {
            core = Runtime.getRuntime().availableProcessors();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return core;
    }

    /**
     * 获取手机分辨率 宽
     *
     * @param c
     */
    public static int phoneWidthPix(Activity c) {
        int screenWidth = 0;
        try {
            Context myContext = c;
            DisplayMetrics dm = c.getResources().getDisplayMetrics();
            screenWidth = dm.widthPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenWidth;
    }

    /**
     * 获取手机分辨率高
     *
     * @param c
     */
    public static int phoneHeightPix(Activity c) {
        int screenHeight = 0;
        try {
            Context myContext = c;
            DisplayMetrics dm = c.getResources().getDisplayMetrics();
            screenHeight = dm.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return screenHeight;
    }


    /**
     * 获取网络运营商名称
     * <p>中国移动、如中国联通、中国电信</p>
     *
     * @return 运营商名称
     */
    public static String getNetworkOperatorName() {
        String opeType = "";
        String operator = "";
        try {
            // No sim
            if (!hasSim(MyApplication.getApplication().getApplicationContext())) {
                return opeType;
            }
            TelephonyManager tm = (TelephonyManager) MyApplication.getApplication().getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
            operator = tm.getSimOperator();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return operator;
    }

    /**
     * 检查手机是否有sim卡
     */
    private static boolean hasSim(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String operator = tm.getSimOperator();
            if (TextUtils.isEmpty(operator)) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 获取当前时区ID  格式为 Asia/Shanghai
     *
     * @return
     */
    public static String getCurrentTimeZone() {
        String timeZoneId = "";
        try {
            TimeZone tz = TimeZone.getDefault();
            timeZoneId = tz.getID();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeZoneId;
    }

    /**
     * 获取当前手机电量
     *
     * @param context
     * @return
     */
    public static int getCurrentLevel(Context context) {
        int currentLevel = 0;
        try {
            BatteryManager manager = (BatteryManager) context.getSystemService(context.BATTERY_SERVICE);
            currentLevel = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentLevel;
    }

    /**
     * 获取 开机时间到现在的时间（13位毫秒）
     *
     * @return
     */
    public static long getTimeToPresent() {
        //public static long elapsedRealtime ()   返回系统启动到现在的毫秒数，包含休眠时间。 参考API
        long time = 0;
        try {
            time = SystemClock.elapsedRealtime();
            if (time < 0) {
                time = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    //没有网络连接
    public static final int NETWORN_NONE = 0;
    //wifi连接
    public static final int NETWORN_WIFI = 1;
    //手机网络数据连接类型
    public static final int NETWORN_2G = 2;
    public static final int NETWORN_3G = 3;
    public static final int NETWORN_4G = 4;
    public static final int NETWORN_5G = 5;
    public static final int NETWORN_MOBILE = 6;


    /**
     * 获取当前网络连接类型
     *
     * @param context
     * @return
     */
    public static int getNetworkState(Activity context) {

        try {
            //获取系统的网络服务
            ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            //如果当前没有网络
            if (null == connManager)
                return NETWORN_NONE;
            //获取当前网络类型，如果为空，返回无网络
            NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
            if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
                return NETWORN_NONE;
            }
            // 判断是不是连接的是不是wifi
            NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (null != wifiInfo) {
                NetworkInfo.State state = wifiInfo.getState();
                if (null != state)
                    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                        return NETWORN_WIFI;
                    }
            }
            // 如果不是wifi，则判断当前连接的是运营商的哪种网络2g、3g、4g等
            NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (null != networkInfo) {
                NetworkInfo.State state = networkInfo.getState();
                String strSubTypeName = networkInfo.getSubtypeName();
                int subtype = activeNetInfo.getSubtype();
                String subtypeName = activeNetInfo.getSubtypeName();
                if (null != state)
                    if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
                        switch (activeNetInfo.getSubtype()) {
                            //如果是2g类型
                            case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
                            case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
                            case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
                            case TelephonyManager.NETWORK_TYPE_1xRTT:
                            case TelephonyManager.NETWORK_TYPE_IDEN:
                            case TelephonyManager.NETWORK_TYPE_GSM:
                                return NETWORN_2G;
                            //如果是3g类型
                            case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
                            case TelephonyManager.NETWORK_TYPE_UMTS:
                            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                            case TelephonyManager.NETWORK_TYPE_HSDPA:
                            case TelephonyManager.NETWORK_TYPE_HSUPA:
                            case TelephonyManager.NETWORK_TYPE_HSPA:
                            case TelephonyManager.NETWORK_TYPE_EVDO_B:
                            case TelephonyManager.NETWORK_TYPE_EHRPD:
                            case TelephonyManager.NETWORK_TYPE_HSPAP:
                            case TelephonyManager.NETWORK_TYPE_IWLAN:
                                return NETWORN_3G;
                            //如果是4g类型
                            case TelephonyManager.NETWORK_TYPE_LTE:
                                return NETWORN_4G;
                            //如果是5G类型
                            case TelephonyManager.NETWORK_TYPE_NR:
                                return NETWORN_5G;
                            default:
                                //中国移动 联通 电信 三种3G制式
                                if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                    return NETWORN_3G;
                                } else {
                                    return NETWORN_MOBILE;
                                }
                        }
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NETWORN_NONE;
    }

    /**
     * 获取当前是wifi 还是 移动网络 再去调用相关方法获取网络ip
     *
     * @param context
     * @return
     */
    public int getCurrentIP(Activity context) {
        //获取系统的网络服务
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //如果当前没有网络
        if (null == connManager) {
            return NETWORN_NONE;
        }
        //获取当前网络类型，如果为空，返回无网络
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
            return NETWORN_NONE;
        }
        //判断是否是WIFI
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (null != wifiInfo) {
            NetworkInfo.State state = wifiInfo.getState();
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {

                    return NETWORN_WIFI;
                }
        }
        return NETWORN_MOBILE;
    }


    /**
     * 获取 外网 IP地址 移动网络 wifi 都可用
     *
     * @return
     */
    public static String line = "";

    public static String GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return line;
    }


    // 获取有限网IP 移动网络获取网络IP地址
    public static String getHostIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()
                            && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }


    /**
     * 获取当前ip地址  没有连接wifi 就返回 0.0.0.0
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }


    /**
     * 获取当前wifi mac地址  直接用
     *
     * @return
     */
    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获取wifi名称 和 wifi 个数   在 android 高版本上面 需要动态权限
     *
     * @return
     */
    public static int wifiCount = 0;//wifi个数
    public static String wifiName = "";//wifi名称

    public static void getWifiNameAndWifiCount(Activity context) {
        wifiCount = 0;
        wifiName = "";
        try {
            WifiManager wifiManager = (WifiManager) MyApplication.getApplication().getApplicationContext().getSystemService(WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            List<ScanResult> results = wifiManager.getScanResults();
            if (null != results) {
                wifiCount = results.size();
            }
            wifiName = wifiInfo.getSSID();
            if (wifiName.contains("unknown")) {
                wifiName = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Log.e("data","wifiCount:"+wifiCount);
        //Log.e("data","wifiName:"+wifiName);
    }

    public static void getPhoto(Activity context) {
        List<India_UserImage_ListBean> userImageListBeanList = new ArrayList<>();
        try {
            Uri uriImage = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver contentResolver = context.getContentResolver();
            Cursor mCursor = contentResolver.query(uriImage, null, MediaStore.Images.Media.MIME_TYPE + "=? or "
                            + MediaStore.Images.Media.MIME_TYPE + " =? ", new String[]{"image/jpeg", "image/png"},
                    MediaStore.Images.Media.DATE_MODIFIED + " desc");
            //mCursor.moveToPosition(mCurrentPosition);
            int i = 0; //查找300条索引图片
            //每次查询300张图片
            while (mCursor.moveToNext() && i < 200) {
                i++;
                //获取图片路径 DATA 常量 需要授予读写权限才可以读取图片
                String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                //照片日期
                long photoDate = mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN));//单位毫秒
                //long photoDate = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));//获取的是秒

                //照片标题
                String photoTitle = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
                if (new File(path).exists()) {
                    India_UserImage_ListBean userImageListBean = new India_UserImage_ListBean();
                    //如果文件存在则加入到自己定义的List中 这里存入的是图片路径
                    //allImagePathList.add(new ImageSelectBean(path, false));
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    //只请求图片宽高，不解析图片像素(请求图片属性但不申请内存，解析bitmap对象，该对象不占内存)
                    opts.inJustDecodeBounds = true;
                    //String path = Environment.getExternalStorageDirectory() + "/dog.jpg";
                    BitmapFactory.decodeFile(path, opts);
                    int imageWidth = opts.outWidth;
                    int imageHeight = opts.outHeight;
                    //照片类型
                    //String photoType = opts.outMimeType;

                    //Log.e("data", "照片路径:" + path);
                    //Log.e("data", "照片日期" + photoDate);
                    //Log.e("data", "照片标题" + photoTitle);
                    //Log.e("data", "照片类型" + photoType);
                    //Log.e("data", "照片长度" + imageWidth);
                    //Log.e("data", "照片宽度" + imageHeight);

                    userImageListBean.setName(photoTitle);
                    userImageListBean.setTime(photoDate);
                    userImageListBean.setWidth(imageWidth);
                    userImageListBean.setHeight(imageHeight);


                    userImageListBean.setMake("");
                    userImageListBean.setModel("");
                    userImageListBean.setLatitude(0);
                    userImageListBean.setLongitude(0);

                    try {
                        ExifInterface exifInterface = new ExifInterface(path);
                        if (null != exifInterface) {
                            String latitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE);//纬度（基于Exif信息）
                            String longitude = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);//经度（基于Exif信息）

                            String make = exifInterface.getAttribute(ExifInterface.TAG_MAKE);//经度（基于Exif信息）
                            String make_model = exifInterface.getAttribute(ExifInterface.TAG_MODEL);//经度（基于Exif信息）
                            //String make_time = exifInterface.getAttribute( ExifInterface.TAG_DATETIME);//经度（基于Exif信息）

                            //Log.e("data", "纬度（基于Exif信息）" + latitude);
                            //Log.e("data", "经度（基于Exif信息）" + longitude);
                            //Log.e("data", "设备品牌" + make);
                            //Log.e("data", "设备型号" + make_model);
                            //Log.e("data","拍摄时间"+make_time);
                            if (TextUtils.isEmpty(make)) {
                                userImageListBean.setMake("");
                            } else {
                                userImageListBean.setMake(make);
                            }
                            if (TextUtils.isEmpty(make_model)) {
                                userImageListBean.setModel("");
                            } else {
                                userImageListBean.setModel(make_model);
                            }
                            userImageListBean.setLatitude(score2dimensionality(latitude));
                            userImageListBean.setLongitude(score2dimensionality(longitude));
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    userImageListBeanList.add(userImageListBean);
                }
            }
            //用完回收
            mCursor.close();

            // Log.e("data",new Gson().toJson(imageBeanList));

            if (userImageListBeanList.size() > 0) {
                //转换格式
                String result = new Gson().toJson(userImageListBeanList);
                //Log.e("data","照片结果:"+result.toString());
                //这里做上传操作
                IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
                Call<String> appList = api.UploadPhotoAlbum(MyPreferencesManager.getString("token", ""), MyApplication.source, new Gson().toJson(userImageListBeanList));
                appList.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {

                        //Log.e("data","上传成功"+response.message().toString());
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        //Log.e("data","上传失败"+t.getMessage().toString());
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将 112/1,58/1,390971/10000 格式的经纬度转换成 112.99434397362694格式
     *
     * @param string 度分秒
     * @return 度
     */
    private static double score2dimensionality(String string) {
        double dimensionality = 0.0;
        try {
            if (null == string) {
                return dimensionality;
            }
            //用 ，将数值分成3份
            String[] split = string.split(",");
            for (int i = 0; i < split.length; i++) {
                String[] s = split[i].split("/");
                //用112/1得到度分秒数值
                double v = Double.parseDouble(s[0]) / Double.parseDouble(s[1]);
                //将分秒分别除以60和3600得到度，并将度分秒相加
                dimensionality = dimensionality + v / Math.pow(60, i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dimensionality;
    }


    /**
     * 获取手机序列号
     *
     * @return 手机序列号
     */
    @SuppressLint("MissingPermission")
    public static String getSerial() {
        String serial = "";
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (serial.contains("unknown")) {
            serial = "";
        }
        return serial;
    }


    /**
     * 获取手机序列号
     *
     * @return 手机序列号
     */
    @SuppressLint({"NewApi", "MissingPermission"})
    public static String getSerialNumber() {
        String serial = "";
        try {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
                serial = Build.SERIAL;
            } else {//8.0-
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method get = c.getMethod("get", String.class);
                serial = (String) get.invoke(c, "ro.serialno");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return serial;
    }


    /**
     * 判断设备 是否使用代理上网
     *
     * @param context 上下文对象
     *                return  当前网络是否开启了代理
     */
    public static boolean isWifiProxy(Context context) {
        try {
            final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
            String proxyAddress;
            int proxyPort;
            if (IS_ICS_OR_LATER) {
                proxyAddress = System.getProperty("http.proxyHost");
                String portStr = System.getProperty("http.proxyPort");
                proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
            } else {
                proxyAddress = android.net.Proxy.getHost(context);
                proxyPort = android.net.Proxy.getPort(context);
            }
            return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isSDMounted() {
        boolean isMounted = false;
        try {
            StorageManager sm = (StorageManager) MyApplication.getApplication().getBaseContext().getSystemService(Context.STORAGE_SERVICE);
            try {
                Method getVolumList = StorageManager.class.getMethod("getVolumeList", null);
                getVolumList.setAccessible(true);
                Object[] results = (Object[]) getVolumList.invoke(sm, null);
                if (results != null) {
                    for (Object result : results) {
                        Method mRemoveable = result.getClass().getMethod("isRemovable", null);
                        Boolean isRemovable = (Boolean) mRemoveable.invoke(result, null);
                        if (isRemovable) {
                            Method getPath = result.getClass().getMethod("getPath", null);
                            String path = (String) mRemoveable.invoke(result, null);
                            Method getState = sm.getClass().getMethod("getVolumeState", String.class);
                            String state = (String) getState.invoke(sm, path);
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                isMounted = true;
                                break;
                            }
                        }
                    }
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return isMounted;
    }


    /**
     * 获取电池容量 mAh
     * <p>
     * 源头文件:frameworks/base/core/res\res/xml/power_profile.xml
     * <p>
     * Java 反射文件：frameworks\base\core\java\com\android\internal\os\PowerProfile.java
     */
    public static double getBatteryCapacity(Context context) {
        Object mPowerProfile;
        double batteryCapacity = 0;
        final String POWER_PROFILE_CLASS = "com.android.internal.os.PowerProfile";

        try {
            mPowerProfile = Class.forName(POWER_PROFILE_CLASS)
                    .getConstructor(Context.class)
                    .newInstance(context);

            batteryCapacity = (double) Class
                    .forName(POWER_PROFILE_CLASS)
                    .getMethod("getBatteryCapacity")
                    .invoke(mPowerProfile);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return batteryCapacity;
    }


    /**
     * 判断手机是否正在充电
     *
     * @param context
     * @return
     */
    public static boolean phoneIsAcCharge(Context context) {
        boolean isCharging = false;//默认没有充电
        try {
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
            //如果设备正在充电，可以提取当前的充电状态和充电方式（无论是通过 USB 还是交流充电器），如下所示：

            // Are we charging / charged?
            int status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return isCharging;
    }

    /**
     * 判断是否是AC充电
     *
     * @param context
     * @return
     */
    public static boolean phoneAcCharge(Context context) {
        boolean isAcCharge = false;//默认没有ac充电
        try {
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
            //如果设备正在充电，可以提取当前的充电状态和充电方式（无论是通过 USB 还是交流充电器），如下所示：
            // Are we charging / charged?
            int status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL;
            // How are we charging?
            int chargePlug = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
            boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
            isAcCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isAcCharge;
    }


    public static String getIMEIS(Context context) {
        String result="";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                result=tm.getImei();
                if(TextUtils.isEmpty(result)){
                    result="";
                }
            } else {
                result=tm.getDeviceId();
                if(TextUtils.isEmpty(result)){
                    result="";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return result;
    }


    /**
     * 判断手机是否开启了usb debug调试功能
     *
     * @param context
     * @return
     */
    public static boolean is_usb_debug(Context context) {
        boolean enableAdb = false;
        try {
            enableAdb = (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return enableAdb;
    }


    /**
     * 是否正在使用VPN
     */
    public static boolean isVpnUsed() {
        try {
            Enumeration niList = NetworkInterface.getNetworkInterfaces();
            if (niList != null) {
                for (Object intf : Collections.list(niList)) {
                    NetworkInterface networkInterface = (NetworkInterface) intf;
                    if (!networkInterface.isUp() || networkInterface.getInterfaceAddresses().size() == 0) {
                        continue;
                    }
                    //Log.d("-----", "isVpnUsed() NetworkInterface Name: " + intf.getName());
                    if ("tun0".equals(networkInterface.getName()) || "ppp0".equals(networkInterface.getName())) {
                        return true; // The VPN is up
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * @return 设备显示的语言: “中文”
     */
    public static String getDisplayLanguage() {
        return Locale.getDefault().getDisplayLanguage();
    }

    /**
     * 设备显示语言前三个字母 缩写: “zhon”
     *
     * @return
     */
    public static String getLocale_iso3_language() {
        return Locale.getDefault().getISO3Language();
    }


    /**
     * 设备选择的国家
     *
     * @return
     */
    public static String getLocale_iso3_country() {
        return Locale.getDefault().getISO3Country();
    }

    /**
     * UUID
     *
     * @return
     */
    public static String getUUID() {
        String uuid = "";
        try {
            uuid = UUID.randomUUID().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uuid;
    }


    /**
     * 获取手机主板名
     */
    public static String getDeviceBoard() {
        String board = "";
        try {
            board = android.os.Build.BOARD;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return board;
    }


    /**
     * 获取键盘类型
     *
     * @return
     */
    public static int getKeyboard() {
        int keyboard = 0;
        try {
            Configuration config = MyApplication.getApplication().getBaseContext().getResources().getConfiguration();
            keyboard = config.keyboard;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return keyboard;
    }


    /**
     * 判断是否是模拟器
     *
     * @return 模拟器
     */
    public static boolean isEmulator() {
        boolean isEmulator = false;
        try {
            isEmulator = Build.FINGERPRINT.startsWith("generic")
                    || Build.FINGERPRINT.toLowerCase().contains("vbox")
                    || Build.FINGERPRINT.toLowerCase().contains("test-keys")
//                || Build.FINGERPRINT.startsWith("unknown") // 魅族MX4: unknown
                    || Build.MODEL.contains("google_sdk")
                    || Build.MODEL.contains("Emulator")
                    || Build.MODEL.contains("Android SDK built for x86")
                    || Build.MANUFACTURER.contains("Genymotion")
                    || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                    || "google_sdk".equals(Build.PRODUCT);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return isEmulator;
    }


    /**
     * 获取sd卡所有的音乐文件
     *
     * @return
     * @throws Exception
     */
    /**
     * 获取本机音乐列表
     * type  0 sdcard上的  1 System系统中的
     *
     * @return
     */
    public static int getMusics(Context context, int type) {
        int videoTotal = 0;
        Cursor c = null;
        try {
            if (type == 0) {
                c = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                        null);
            } else if (type == 1) {
                c = context.getContentResolver().query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, null, null, null,
                        null);
            }
            while (c.moveToNext()) {
                videoTotal++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return videoTotal;
    }

    /**
     * 得到download文件夹下的文件个数
     *
     * @param path
     * @return
     */
    public static int getAllDataFileName(String path) {
        int download_files = 0;
        try {
            String filename;//文件名
            String suf;//文件后缀
            File dir = new File(path);//文件夹dir
            File[] files = dir.listFiles();//文件夹下的所有文件或文件夹
            if (files == null)
                return 0;
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    System.out.println("---" + files[i].getAbsolutePath());
                    getAllDataFileName(files[i].getAbsolutePath());//递归文件夹！！！
                } else {
                    download_files++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return download_files;
    }


    /**
     * 获取本地所有的图片
     * type 0 sdcard上的图片个数  1 System内部的图片个数
     *
     * @return list
     */
    public static int getAllLocalPhotos(Context context, int type) {
        int totalUploadCount = 0;
        try {
            String[] projection = {
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media.DISPLAY_NAME,
                    MediaStore.Images.Media.SIZE
            };
            //全部图片
            String where = MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Images.Media.MIME_TYPE + "=?";
            //指定格式
            String[] whereArgs = {"image/jpeg", "image/png", "image/jpg", "image/webp"};
            //查询
            Cursor cursor = null;
            if (type == 0) {
                cursor = context.getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, where, whereArgs,
                        MediaStore.Images.Media.DATE_MODIFIED + " desc ");
            } else if (type == 1) {
                cursor = context.getContentResolver().query(
                        MediaStore.Images.Media.INTERNAL_CONTENT_URI, projection, where, whereArgs,
                        MediaStore.Images.Media.DATE_MODIFIED + " desc ");
            }
            if (cursor == null) {
                return 0;
            }
            //遍历
            while (cursor.moveToNext()) {
                totalUploadCount++;
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalUploadCount;
    }


    /**
     * 获取本地所有的视频
     * type 0 sdcard个数  1 System个数
     *
     * @return list
     */
    public static int getAllLocalVideos(Context context, int type) {
        int videoTotal = 0;
        try {
            String[] projection = {
                    MediaStore.Video.Media.DATA,
                    MediaStore.Video.Media.DISPLAY_NAME,
                    MediaStore.Video.Media.DURATION,
                    MediaStore.Video.Media.SIZE
            };
            //全部图片
            String where = MediaStore.Images.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=? or "
                    + MediaStore.Video.Media.MIME_TYPE + "=?";
            String[] whereArgs = {"video/mp4", "video/3gp", "video/aiv", "video/rmvb", "video/vob", "video/flv",
                    "video/mkv", "video/mov", "video/mpg"};
            Cursor cursor = null;
            if (type == 0) {
                cursor = context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                        projection, where, whereArgs, MediaStore.Video.Media.DATE_ADDED + " DESC ");
            } else if (type == 1) {
                cursor = context.getContentResolver().query(MediaStore.Video.Media.INTERNAL_CONTENT_URI,
                        projection, where, whereArgs, MediaStore.Video.Media.DATE_ADDED + " DESC ");
            }

            if (cursor == null) {
                return 0;
            }
            try {
                while (cursor.moveToNext()) {
                    videoTotal++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return videoTotal;
    }


    /**
     * 设备唯一id 保存在手机公共文件夹下 及 app 缓存里面
     *
     * @return
     */
    public static String getDeviceID(Context context) {
        //内存中获取deviceId
        String deviceId = "";
        try {
            deviceId = MyPreferencesManager.getDeviceID();
            if (!TextUtils.isEmpty(deviceId)) {

                return deviceId;
            }
            //获取公共文件夹里面的deviceId
            String tagName = context.getResources().getString(R.string.app_name);
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + tagName + ".txt";
            File file = new File(path);
            if (file.exists()) {
                deviceId = getFileContent(file);
                if (!TextUtils.isEmpty(deviceId)) {
                    return deviceId;
                }
            }

            //上面两张方式都没有获取到 deviceId  那么久重新生成 deviceId 并且保存
            deviceId = getIMEI(context);
            if (!TextUtils.isEmpty(deviceId)) {
                return deviceId;
            }

            deviceId = Settings.System.getString(MyApplication.getApplication().getBaseContext().getContentResolver(), Settings.System.ANDROID_ID);
            if (!TextUtils.isEmpty(deviceId)) {
                return deviceId;
            }

            //ime 和 androidId 都没有获取到 就生成一个UUID
            deviceId = getUUID();
            if (!TextUtils.isEmpty(deviceId)) {
                //保存deviceId
                UniqueDeviceUtilsID uniqueDeviceUtilsID = new UniqueDeviceUtilsID();
                uniqueDeviceUtilsID.saveTextFile(context, deviceId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return deviceId;
    }


    //读取指定目录下的所有TXT文件的文件内容
    private static String getFileContent(File file) {
        String content = "";
        try {
            if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
                if (file.getName().endsWith("txt")) {//文件格式为""文件
                    try {
                        InputStream instream = new FileInputStream(file);
                        if (instream != null) {
                            InputStreamReader inputreader
                                    = new InputStreamReader(instream, "UTF-8");
                            BufferedReader buffreader = new BufferedReader(inputreader);
                            String line = "";
                            //分行读取
                            while ((line = buffreader.readLine()) != null) {
                                content += line + "\n";
                            }
                            instream.close();//关闭输入流
                        }
                    } catch (java.io.FileNotFoundException e) {
                        Log.d("TestFile", "The File doesn't not exist.");
                    } catch (IOException e) {
                        Log.d("TestFile", e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 获取手机IMSI
     */
    public static String getIMSI(Context context) {
        try {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            //获取IMSI号
            String imsi = telephonyManager.getSubscriberId();
            if (null == imsi) {
                imsi = "";
            }
            return imsi;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 用于首次安装时的使用 其它地方不使用
     *
     * @return
     */
    public static String getUUIDInstall() {
        String uuid = "000000000";
        try {
            uuid = UUID.randomUUID().toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uuid;
    }

}
